package com.tnl.hunter.webchat.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.biz.hunter.dao.HunterCompanyDAO;
import com.biz.hunter.dao.HunterDAO;
import com.biz.hunter.dao.WXUserDAO;
import com.biz.hunter.db.entity.Hunter;
import com.biz.hunter.db.entity.HunterCompany;
import com.biz.hunter.db.entity.UserInfo;
import com.biz.hunter.db.entity.jsConfig;
import com.biz.qq.wechat.api.MediaAPI;
import com.biz.system.config.WebchatServiceConstant;
import com.biz.wechat.annotation.OAuthRequired;
import com.biz.wechat.util.SignUtil;
import com.tnl.hunter.dto.CompanyDto;

@Controller
public class HunterCompanyController {

	private static final Logger logger = LoggerFactory.getLogger(HunterCompanyController.class);

	@Autowired
	private HunterCompanyDAO hunterCompanyDAO;
	@Autowired
	private HunterDAO hunterDAO;
	@Autowired
	private WXUserDAO userDAO;
	@Autowired
	private SysConfigRepo sysConfigService;

	// 猎头认证创建公司第一页
	@OAuthRequired
	@RequestMapping(value = "wechat/hunterCompany/toCreate.page", method = RequestMethod.GET)
	public String toCreateCompany(HttpServletRequest request, int hunterId, Model model) {
		
		HttpSession session = request.getSession();
		
		String openid = (String) session.getAttribute("OpenId");
		logger.debug("openid is " + openid);
		if (!StringUtils.hasText(openid)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}

		UserInfo user = userDAO.getByOpenId(openid);
		if (user == null) {
			logger.info("the openid " + openid + " is not subscribed");
			return "wechat/headhunter/errorpage";
		}
		
		Hunter hunter = hunterDAO.getByActivateHunter(openid);
		if (hunter == null) {
			return "wechat/headhunter/errorpage";
		}
		if(hunter.getId() != hunterId) {
			model.addAttribute("title","温馨提示" );
			model.addAttribute("errormsg", "系统错误, 猎头用户不存在");
			return "wechat/headhunter/msgpage";
		}

		int compId = hunter.getCompanyId();
		HunterCompany comp = hunterCompanyDAO.getById(compId);
		if (comp != null) {
			model.addAttribute("company", comp);
		}
		model.addAttribute("hunter", hunter);
		List<HunterCompany> companies = hunterCompanyDAO.getALL();
		model.addAttribute("companies", companies);
		
		/* */
		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is "+ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {  
	        url = url + "?" + request.getQueryString();  
	    } 
		logger.debug("request url is " + url);
			
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
			
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
			
		model.addAttribute("config", config);
		/* */


		return "wechat/headhunter/hunter/lietouxinxi21";
	}
	
	// 新版
	@OAuthRequired
	@RequestMapping(value = "wechat/hunterCompany/create2_2.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> createCompanyStep2_2( HttpServletRequest request, ModelMap model, CompanyDto dto) {
		
		Map<String, Object> returnMap = new HashMap<String, Object>();
		
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		
		if (!StringUtils.hasText(openId)) {
			logger.info("您需要在微信平台使用");
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "您需要在微信平台使用");
			return returnMap;
		}

		int hunterId = dto.getHunterid();
		if (hunterId == 0) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "必须提供猎头信息");
			return returnMap;
		}
		Hunter hunter = hunterDAO.getById(hunterId);
		if (hunter == null) {
			returnMap.put("errorcode", "2");
			returnMap.put("msg", "该猎头信息不存在");
			return returnMap;
		}
		
		// 分情况进行处理
		String companyname = dto.getCompanyname();
		String bizcode = dto.getBizcode();
		
		HunterCompany cp = hunterCompanyDAO.getByName(companyname);
		if(cp == null) {
			// 猎头的公司不在数据库里，那么需要创建猎头公司
			session.setAttribute("hunterCompanyDTO", dto);
			returnMap.put("errorcode","1");
			returnMap.put("msg", "请继续创建公司信息");
			return returnMap;
		} else {
			// 如果数据库里已经有该公司的了，那么检查营业执照代码是否正确
			if(bizcode.compareToIgnoreCase(cp.getLicenseCode()) == 0) {
				// 检查绑定是否超过限制
				Long count = hunterDAO.getBindedByCompanyIdCount(cp.getId());
				if(count > 4) {
					hunter.setBinded(-1);
					hunter.setCompanyId(cp.getId());
					hunter.setCompanyName(cp.getName());
					hunterDAO.update(hunter);
					returnMap.put("errorcode","3");
					returnMap.put("msg", "该公司绑定人数已超限制");
					return returnMap;
				}
				// 绑定它
				hunter.setBinded(0);
				hunter.setCompanyId(cp.getId());
				hunter.setCompanyName(cp.getName());
				int result = hunterDAO.update(hunter);
				if(result == -1) {
					returnMap.put("errorcode","-3");
					returnMap.put("msg", "操作失败");
					return returnMap;
				}
				returnMap.put("errorcode","0");
				returnMap.put("msg", "公司成功绑定");
				return returnMap;
			} else {
				// 提示错误
				returnMap.put("errorcode","3");
				returnMap.put("msg", "你输入的公司名已经存在系统中，但和公司的营业执照代码不匹配");
				return returnMap;
			}
		}
	}
		
	// 新版：猎头认证创建公司第二页
	@OAuthRequired
	@RequestMapping(value = "wechat/hunterCompany/toCreate2_2.page", method = RequestMethod.GET)
	public String toCreateCompanyStep2_2(HttpServletRequest request, Model model) {
		
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");

		logger.debug("openid is " + openid);
		if (!StringUtils.hasText(openid)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}
		
		Hunter hunter = hunterDAO.getByActivateHunter(openid);
		if (hunter == null) {
			logger.error("the input parameter is not correct");
			model.addAttribute("title","温馨提示" );
			model.addAttribute("msg", "对话超时，需要重新进入");
			return "wechat/headhunter/msgpage";
		}
		model.addAttribute("hunter", hunter);
		
		CompanyDto cp = (CompanyDto)session.getAttribute("hunterCompanyDTO");
		HunterCompany company = new HunterCompany();
		company.setLicenseCode(cp.getBizcode());
		company.setName(cp.getCompanyname());
		
		model.addAttribute("company", company);
		
		/* */
		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is "+ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {  
	        url = url + "?" + request.getQueryString();  
	    } 
		logger.debug("request url is " + url);
			
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
			
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
			
		model.addAttribute("config", config);
		/* */

		
		return "wechat/headhunter/hunter/lietouxinxi22";
	}

	// 新版
	@OAuthRequired
	@RequestMapping(value = "wechat/hunterCompany/create1_2.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> createCompanyStep1_2(HttpServletRequest request, ModelMap model, CompanyDto dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");
		
		if (!StringUtils.hasText(openid)) {
			logger.info("您需要在微信平台使用");
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "您需要在微信平台使用");
			return returnMap;
		}

		int hunterId = dto.getHunterid();
		if (hunterId == 0) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "必须先提交猎头信息");
			return returnMap;
		}
		//Hunter hunter = hunterDAO.getById(hunterId);
		Hunter hunter = hunterDAO.getByActivateHunter(openid);
		if (hunter == null) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "该猎头信息不存在");
			return returnMap;
		}
		if(hunter.getId() != hunterId) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "提交的猎头信息不一致");
			return returnMap;
		}
		
		session.removeAttribute("hunterCompanyDTO");
		
		String companyname = dto.getCompanyname();
		HunterCompany company = hunterCompanyDAO.getByName(companyname);
		
		if(company!=null) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "该公司已经存在系统当中，请和管理员联系");
			return returnMap;
		}
		
		// 那就创建新公司
		HunterCompany htcompany = new HunterCompany();
		htcompany.setName(dto.getCompanyname());
		htcompany.setContact(dto.getCompanycontact());
		htcompany.setAddress(dto.getCompanyaddress());
		htcompany.setPhone(dto.getCompanyphone());
		htcompany.setLicenseCode(dto.getBizcode());
		htcompany.setOrgnizationCode(dto.getOrgcode());
		htcompany.setApproved(0);
		Date now = new Date();
		htcompany.setCreateDate(now.getTime());
		int result = hunterCompanyDAO.save(htcompany);
		if (result == -1) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "创建公司失败，请和管理员联系");
			return returnMap;
		}
		int companyid = result;
		htcompany.setId(companyid);
		
		// 更新hunter信息， 绑定它
		hunter.setBinded(0);
		hunter.setCompanyId(htcompany.getId());
		hunter.setCompanyName(htcompany.getName());
		result = hunterDAO.update(hunter);
		if(result == -1) {
			returnMap.put("errorcode","40001");
			returnMap.put("msg", "操作失败");
			return returnMap;
		}
		returnMap.put("errorcode","0");
		returnMap.put("msg", "公司成功创建并绑定");
		return returnMap;
	}

	

	@OAuthRequired
	@RequestMapping(value = "wechat/hunterCompany/uploadFile.do", method = RequestMethod.GET)
	public String uploadFile(HttpServletRequest request, int companyId, String resId, Model model) {
		
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		if (!StringUtils.hasText(openId)) {
			logger.info("session过期,请关闭重试");
			return "wechat/headhunter/errorPage";
		}
		
		//String realPath = request.getSession().getServletContext().getRealPath("/resources/images/huntercompany");
		String realPath = FileController.BASE_PATH;
		logger.debug("path is " + realPath);
		
		String token = sysConfigService.getAccessToken();

		logger.debug("getMedia()");
	
		HunterCompany company = hunterCompanyDAO.getById(companyId);
		if (company==null){
			logger.error("invalid input parameter about hrId");
			return "wechat/headhunter/errorPage";
		}
		company.setImageUrl(resId);
		hunterCompanyDAO.update(company);
			
		Map<String, Object> result = MediaAPI.getMediaFromWechat(realPath, resId, token);
		
		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is "+ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {  
            url = url + "?" + request.getQueryString();  
        } 
		logger.debug("request url is " + url);
		
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		
		model.addAttribute("config", config);
		
		return "wechat/headhunter/hunter/lietouxinxi31";	
	}

	/*
	// 猎头认证创建公司第二页
	//@OAuthRequired
	@RequestMapping(value = "wechat/hunterCompany/toCreate2.page", method = RequestMethod.GET)
	public String toCreateCompanyStep2(HttpServletRequest request, int hunterId, int companyId, Model model) {
		
		Hunter hunter = hunterDAO.getById(hunterId);

		if (hunter == null) {
			logger.error("the input parameter is not correct");
			model.addAttribute("message", "the input parameter about the hunter is not correct");
			return "wechat/headhunter/errorpage";
		}
		model.addAttribute("hunter", hunter);
		List<HunterCompany> companies = hunterCompanyDAO.getALL();
		model.addAttribute("companies", companies);

		int compId = hunter.getCompanyId();
		//String compName = hunter.getCompanyName();
		
		
		HunterCompany comp = hunterCompanyDAO.getById(compId);
		if (comp != null) {
			model.addAttribute("company", comp);
		}
		if (comp.getApproved()==1) {
			logger.error("the hunter is already binded the authrized company");
        	return "wechat/headhunter/hunter/lietouxinxi3";
		}
		logger.debug("it is a temp binded company");
		return "wechat/headhunter/hunter/lietouxinxi22";
	}
	*/

	/*
	//@OAuthRequired
	@RequestMapping(value = "wechat/hunterCompany/create.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> createCompanyStep1(
			HttpServletRequest request, ModelMap model, CompanyDto dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		int result = -1;
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");

		int hunterId = dto.getHunterid();
		if (hunterId == 0) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hunerId");
			return returnMap;
		}
		Hunter hunter = hunterDAO.getById(hunterId);
		if (hunter == null) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg",
					"invalid paramter in request for the hunter id = "
							+ hunterId);
			return returnMap;
		}

		int companyId = persistentCompany(dto);
		if (companyId == -1) {
			returnMap.put("errorcode", "50105");
			returnMap.put("msg", " failed to persistent the hunter company ("
					+ dto.getCompanyname() + ")  Id =" + dto.getCompanyid());
			returnMap.put("data", companyId);
			return returnMap;
		}
		result = bindCompany(hunterId, companyId);

		if (result == -1) {
			returnMap.put("errorcode", "50106");
			returnMap.put("msg", " failed to bind the hunter (" + hunterId
					+ ") to company Id =" + companyId);
			returnMap.put("data", companyId);
			return returnMap;
		}

		returnMap.put("errorcode", "200");
		returnMap.put("msg", "create company successfully");
		returnMap.put("data", companyId);
		return returnMap;
	}
	
	//@OAuthRequired
	@RequestMapping(value = "wechat/hunterCompany/create2.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> createCompanyStep2(HttpServletRequest request, ModelMap model, CompanyDto dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		int result = -1;
		
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		
		if (!StringUtils.hasText(openId)) {
			logger.info("您需要在微信平台使用");
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "您需要在微信平台使用");
			return returnMap;
		}

		int hunterId = dto.getHunterid();
		if (hunterId == 0) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hunerId");
			return returnMap;
		}
		Hunter hunter = hunterDAO.getById(hunterId);
		if (hunter == null) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg",
					"invalid paramter in request for the hunter id = "
							+ hunterId);
			return returnMap;
		}

		int companyId = persistentCompany(dto);
		if (companyId == -1) {
			returnMap.put("errorcode", "50105");
			returnMap.put("msg", " failed to persistent the hunter company ("
					+ dto.getCompanyname() + ")  Id =" + dto.getCompanyid());
			returnMap.put("data", companyId);
			return returnMap;
		}
		result = bindCompany(hunterId, companyId);

		if (result == -1) {
			returnMap.put("errorcode", "50106");
			returnMap.put("msg", " failed to bind the hunter (" + hunterId
					+ ") to company Id =" + companyId);
			returnMap.put("data", companyId);
			return returnMap;
		}

		returnMap.put("errorcode", "200");
		returnMap.put("msg", "create company successfully");
		returnMap.put("data", companyId);
		return returnMap;
	}
	*/
	

	/*
	//@OAuthRequired
	@RequestMapping(value = "wechat/hunterCompany/bindCompany.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> bindCompany(
			HttpServletRequest request, ModelMap model, CompanyDto dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		int result = -1;
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("openId");
		String orgcode = dto.getOrgcode();
		int hunterId = dto.getHunterid();
		int companyId = dto.getCompanyid();
		if (!StringUtils.hasText(orgcode)) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the orgcode");
			return returnMap;
		}

		if (companyId == 0) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg",
					"invalid paramter in request for the companyId");
			return returnMap;
		}

		if (hunterId == 0) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "invalid paramter in request for the hunerId");
			return returnMap;
		}
		Hunter hunter = hunterDAO.getById(hunterId);
		if (hunter == null) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg",
					"invalid paramter in request for the hunter id = "
							+ hunterId);
			return returnMap;
		}

		HunterCompany company = hunterCompanyDAO.getById(companyId);

		if (company == null) {
			returnMap.put("errorcode", "50105");
			returnMap.put("msg", " failed to get the hunter company ( Id ="
					+ dto.getCompanyid());
			returnMap.put("data", companyId);
			return returnMap;
		}

		if (orgcode.equals(company.getOrgnizationCode())) {
			result = bindCompany(hunterId, companyId);
			if (result == -1) {
				returnMap.put("errorcode", "50106");
				returnMap.put("msg", " failed to bind the hunter (" + hunterId
						+ ") to company Id =" + companyId);
				returnMap.put("data", companyId);
				return returnMap;
			}
		}
		else{
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "the orgcode is not correct");
			returnMap.put("data", companyId);
			return returnMap;
		}

		returnMap.put("errorcode", "200");
		returnMap.put("msg", "create company successfully");
		returnMap.put("data", companyId);
		return returnMap;
	}
	
	private int persistentCompany(CompanyDto dto) {
		String companyname = dto.getCompanyname();
		int companyId = dto.getCompanyid();
		HunterCompany comp = hunterCompanyDAO.getById(companyId);
		if (comp != null) {// update
			// 认证通过，不再update
			if (comp.getApproved() == 1) {
				return companyId;
			}
			comp.setName(dto.getCompanyname());
			comp.setContact(dto.getCompanycontact());
			comp.setAddress(dto.getCompanyaddress());
			// comp.setEmail(dto.);
			comp.setPhone(dto.getCompanyphone());
			comp.setLicenseCode(dto.getBizcode());
			comp.setOrgnizationCode(dto.getOrgcode());
			int result = hunterCompanyDAO.update(comp);
			if (result == -1) {
				logger.error("failed to update hunter comapny" + companyId);
				return -1;
			}
			return companyId;
		}

		// create new company
		comp = new HunterCompany();
		comp.setName(dto.getCompanyname());
		comp.setContact(dto.getCompanycontact());
		comp.setAddress(dto.getCompanyaddress());
		// comp.setEmail(dto.);
		comp.setPhone(dto.getCompanyphone());
		comp.setLicenseCode(dto.getBizcode());
		comp.setOrgnizationCode(dto.getOrgcode());
		comp.setApproved(0);
		Date now = new Date();
		comp.setCreateDate(now.getTime());
		int result = hunterCompanyDAO.save(comp);
		if (result == -1) {
			logger.error("failed to update hunter comapny" + comp.getName());
			return -1;
		}
		companyId = result;

		return companyId;
	}

	private int bindCompany(int hunterId, int companyId) {

		Hunter hunter = hunterDAO.getById(hunterId);
		logger.debug("update the hunter info with the companyid " + companyId);
		List<Hunter> list = hunterDAO.getBindedByCompanyId(companyId);
		if (list == null || list.size() <= 4) {
			hunter.setBinded(0);
		} else {
			logger.info("there are 5 person binded the company with id ="
					+ companyId);
			hunter.setBinded(-1);
		}
		hunter.setCompanyId(companyId);
		int result = hunterDAO.update(hunter);
		return result;
	}
	
	//@OAuthRequired
	@RequestMapping(value = "wechat/hunterCompany/toEdit.page", method = RequestMethod.GET)
	public String toEditCompany(HttpServletRequest request, int hunterId, int companyId, Model model) {
		Hunter hunter = hunterDAO.getById(hunterId); 
		model.addAttribute("hunter", hunter); 
		HunterCompany company = hunterCompanyDAO.getById(companyId); 
		model.addAttribute("company", company); 
		List<HunterCompany> companies = hunterCompanyDAO.getALL(); 
		model.addAttribute("companies", companies); 
		return "wechat/headhunter/hunter/lietouxinxi2";
	}
	*/
	

}
